package com.hxl.tech.gateway.auth.service;


import com.hxl.tech.gateway.auth.dao.ResourceDao;
import com.hxl.tech.gateway.auth.dto.resource.ResourceFindDTO;
import com.hxl.tech.gateway.auth.model.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Objects;

/**
 * 资源配置 Service 
 * @author soliddq
 * @date 2023-10-10
 */
@Service
@RequiredArgsConstructor
@Transactional
public class ResourceService {

    private final ResourceDao resourceDao;
    private final EntityManager entityManager;

    public List<Resource> find(ResourceFindDTO findDTO) {

        return resourceDao.find(findDTO);
    }

    public Resource read(Resource.Id id) {

        return resourceDao.read(id.getMerchantCode(), id.getResourceType());
    }


    public Resource saveOrUpdate(Resource resource) {

        Resource origResource = this.read(resource.getId());
        if (Objects.isNull(origResource)) {
            entityManager.persist(resource);
        } else {
            entityManager.merge(resource);
        }
        return resource;
    }

    public void delete(Resource.Id id) {

        Resource origResource = this.read(id);
        if (Objects.nonNull(origResource)) {
            entityManager.remove(origResource);
        }
    }
}
